package se.plingapp.enterprisebeans;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import se.plingapp.entitybeans.User;

/**
 * User business.
 *
 * @author Jens Ljungblad
 */
@Stateless
public class UserFacade extends AbstractFacade<User> {

    /**
     * Entity manager with a given persistence context.
     */
    @PersistenceContext(unitName = "PlingPU")
    private EntityManager em;

    /**
     * Implemented method from abstract facade.
     */
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    /**
     * Constructor.
     */
    public UserFacade() {
        super(User.class);
    }

    /**
     * Perform a case-insensitive search on name and e-mail.
     *
     * @param search
     * @return List of users
     */
    public List<User> find(String search) {
        TypedQuery<User> query = getEntityManager().createQuery("SELECT u FROM User u WHERE LOWER(u.name) LIKE :search OR LOWER(u.email) LIKE :search", User.class);
        if(search != null)
            query.setParameter("search", "%" + search.toLowerCase() + "%");
        else
            query.setParameter("search", "%");
        return query.getResultList();
    }

    public List<User> findFollowersByUser(User user) {
        TypedQuery<User> query = getEntityManager().createQuery("SELECT u FROM User u WHERE :user MEMBER OF u.follows", User.class);
        query.setParameter("user", user);
        return query.getResultList();
    }

    /**
     * Find a single user based on e-mail address.
     *
     * @param email
     * @return Matching user, or null
     */
    public User findByEmail(String email) {
        TypedQuery<User> query = getEntityManager().createQuery("SELECT u FROM User u WHERE u.email = :email", User.class);
        query.setParameter("email", email);
        try {
            return query.getSingleResult();
        } catch(NoResultException e) {
            return null;
        }
    }

}
